### get external defined data

LIBLORAGW_VERSION := 0.1.2
include library.cfg

### constant symbols

ARCH ?= arm
CROSS_COMPILE ?= arm-linux-gnueabihf-
CC := $(CROSS_COMPILE)gcc
AR := $(CROSS_COMPILE)ar

CFLAGS := -g -O2 -Wall -Wextra -fPIC -std=c99 -D_POSIX_C_SOURCE=200112L -D_BSD_SOURCE -Iinc -I.

CFLAGS += $(GLOBAL_CFLAGS)
#EXTRA_FLAGS=-DSPI_SPEED=$(GW_SPI_SPEED) -DSPI_DEV_PATH=\"$(GW_SPI_DEVICE)\"

OBJDIR = obj
LIBDIR = lib
INCLUDES = $(wildcard inc/*.h)

### linking options

LIBS := -lsx1301 -lrt -lm -L./$(LIBDIR)

### general build targets

all: dirs libsx1301.a libsx1301.so

clean:
	rm -f $(LIBDIR)/libsx1301.a
	rm -f $(LIBDIR)/libsx1301.so    
	rm -f $(OBJDIR)/*.o
	rm -f inc/config.h
	rm -rf $(OBJDIR)
	rm -rf $(LIBDIR)

### transpose library.cfg into a C header file : config.h

inc/config.h: library.cfg
	@echo "*** Checking libloragw library configuration ***"
	@rm -f $@
    # File initialization
	@echo "#ifndef _LORAGW_CONFIGURATION_H" >> $@
	@echo "#define _LORAGW_CONFIGURATION_H" >> $@
    # Release version
	@echo "Release version   : $(LIBLORAGW_VERSION)"
	@echo "	#define LIBLORAGW_VERSION	"\"$(LIBLORAGW_VERSION)\""" >> $@
    # Debug options
	@echo "	#define DEBUG_AUX	$(DEBUG_AUX)" >> $@
	@echo "	#define DEBUG_SPI	$(DEBUG_SPI)" >> $@
	@echo "	#define DEBUG_REG	$(DEBUG_REG)" >> $@
	@echo "	#define DEBUG_HAL	$(DEBUG_HAL)" >> $@
	@echo "	#define DEBUG_GPS	$(DEBUG_GPS)" >> $@
	@echo "	#define DEBUG_LBT	$(DEBUG_LBT)" >> $@
    # end of file
	@echo "#endif" >> $@
	@echo "*** Configuration seems ok ***"

### library module target

dirs:
	@mkdir -p $(OBJDIR)
	@mkdir -p $(LIBDIR)

$(OBJDIR)/%.o: src/%.c $(INCLUDES) inc/config.h | $(OBJDIR)
	$(CC) -c $(CFLAGS) $< -o $@

$(OBJDIR)/loragw_spi.o: src/loragw_spi.native.c $(INCLUDES) inc/config.h | $(OBJDIR)
	$(CC) -c $(CFLAGS) $(EXTRA_FLAGS) $< -o $@

$(OBJDIR)/loragw_hal.o: src/loragw_hal.c $(INCLUDES) src/arb_fw.var src/agc_fw.var src/cal_fw.var inc/config.h | $(OBJDIR)
	$(CC) -c $(CFLAGS) $< -o $@

### static library

libsx1301.a: $(OBJDIR)/loragw_hal.o $(OBJDIR)/loragw_reg.o $(OBJDIR)/loragw_spi.o $(OBJDIR)/loragw_aux.o $(OBJDIR)/loragw_radio.o $(OBJDIR)/loragw_fpga.o $(OBJDIR)/loragw_lbt.o
	$(AR) rcs $(LIBDIR)/$@ $^

### dynamic library
libsx1301.so: $(OBJDIR)/loragw_hal.o $(OBJDIR)/loragw_reg.o $(OBJDIR)/loragw_spi.o $(OBJDIR)/loragw_aux.o $(OBJDIR)/loragw_radio.o $(OBJDIR)/loragw_fpga.o $(OBJDIR)/loragw_lbt.o
	$(CC) -shared -fPIC -o $(LIBDIR)/$@ $^
    
### test programs


### EOF

